package com.tzxs.pay.util.websocket;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tzxs.pay.main.gt.broadcast.NoticeReceiver;
import com.tzxs.pay.util.ApiService;
import com.tzxs.pay.util.ISharedPreference;
import com.tzxs.pay.util.websocket.model.WebSocketBean;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.lang.ref.WeakReference;
import java.net.URI;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class NoticeWebSocket extends WebSocketClient {
    private static final String TAG = NoticeWebSocket.class.getSimpleName();

    private WeakReference<Application> weakReference;

    private Context context;

    public void setWeakReference(WeakReference<Application> weakReference) {
        this.weakReference = weakReference;
    }

    public NoticeWebSocket(URI serverUri, Context context) {
        super(serverUri);
        this.context = context;
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        Log.d(TAG, "onOpen: getHttpStatus---  " + handshakedata.getHttpStatus());
        Log.d(TAG, "onOpen: getHttpStatusMessage---  " + handshakedata.getHttpStatusMessage());

    }

    @Override
    public void onMessage(String message) {

        Log.d(TAG, "onMessage: 内容:" + message);

        Gson gson = new Gson();
        WebSocketBean bean = gson.fromJson(message, new TypeToken<WebSocketBean>() {
        }.getType());

        if (bean.getClient_id() != null) {
            bean.setLogin_type("2");
            bean.setUser_phone(ISharedPreference.getInstance(weakReference.get()).getPhone());
            //收到数据登录
            login(bean.getType(), bean.getLogin_type(), bean.getClient_id(), bean.getUser_phone());
        }
        if (bean.getMsg() != null) {//当收到消息直接发送广播
            Log.d(TAG, "onMessage: 发送广播消息:" + message);
            WebSocketBean.MsgBean msg = bean.getMsg();
            Intent intent = new Intent();
            intent.setAction(NoticeReceiver.action);
            intent.putExtra("msg", msg);
            context.sendBroadcast(intent);
        }


    }


    @Override
    public void onClose(int code, String reason, boolean remote) {

        Log.d(TAG, "onClose: code:" + code + "reason:" + reason + "remote:" + remote);

    }

    @Override
    public void onError(Exception ex) {

    }


    //websocket连接成功后登录
    private void login(String type, String login_type, String client_id, String phone) {

        Log.d(TAG, "login: 请求的参数:" + "type: " + type + "login_type: " + login_type + "client_id: " + client_id + "phone: " + phone);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiService.mainlogin)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        retrofit.create(ApiService.class)
                .loginWebSocket(type, login_type, client_id, phone)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<WebSocketBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                        Log.d(TAG, "onSubscribe: 走这里了么");
                    }

                    @Override
                    public void onNext(WebSocketBean response) {

                        Log.d(TAG, "onNext: 获取数据的结果:" + new Gson().toJson(response));


                    }

                    @Override
                    public void onError(Throwable e) {

                        Log.d(TAG, "onError: 请求错误" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        Log.d(TAG, "onComplete: 请求完成");
                    }
                });

    }


}

